package com.ivr.cm.service.impl;

import java.util.AbstractMap;

import org.apache.log4j.Logger;
import org.springframework.core.task.TaskExecutor;

import com.ivr.cm.service.BaseServiceIF;

/**
 * 数据库服务,根据class名字查找对应的处理类
 * 实现了异步入库。
 * 调用者无需关心同步还是异步
 * @author liugeng
 * 2015-12-16
 *
 */
public class DbService implements BaseServiceIF<Object> {
	private static Logger logger = Logger.getLogger(DbService.class);
	
	private TaskExecutor dbtaskExecutor;
	private AbstractMap<String,BaseServiceIF<Object>> services;

	@Override
	public int doProcess(Object obj) {
		String className = obj.getClass().getName();
		logger.info(String.format("[%s]开始异步入库操作!", className));
		
		BaseServiceIF<Object> service = services.get(className);
		if (service != null){
			DbHandleThread dbHandleThread = new DbHandleThread(service,obj);
			dbtaskExecutor.execute(dbHandleThread);
		}
		
		return 0;
	}

	public TaskExecutor getDbtaskExecutor() {
		return dbtaskExecutor;
	}
	public void setDbtaskExecutor(TaskExecutor dbtaskExecutor) {
		this.dbtaskExecutor = dbtaskExecutor;
	}
	public AbstractMap<String, BaseServiceIF<Object>> getServices() {
		return services;
	}
	public void setServices(AbstractMap<String, BaseServiceIF<Object>> services) {
		this.services = services;
	}
}

class DbHandleThread implements Runnable{
	private BaseServiceIF<Object> service;
	private Object obj;
	
	public DbHandleThread(BaseServiceIF<Object> service, Object obj){
		this.service = service;
		this.obj=obj;
	}

	@Override
	public void run() {
		service.doProcess(obj);
	}
}